<template>
  <q-dialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    persistent
  >
    <q-card style="min-width: 400px">
      <q-card-section>
        <div class="text-h6">{{ isEditMode ? '编辑用户' : '新增用户' }}</div>
      </q-card-section>

      <q-form @submit.prevent="onSubmit">
        <q-card-section class="q-pt-none">
          <q-input
            v-model="formData.name"
            label="用户名"
            :rules="[(val) => !!val || '用户名不能为空']"
            autofocus
          />
          <q-input
            v-model="formData.email"
            label="邮箱"
            type="email"
            :rules="[(val) => !!val || '邮箱不能为空']"
          />
          <q-select
            v-model="formData.status"
            :options="['启用', '禁用']"
            label="状态"
            :rules="[(val) => !!val || '请选择状态']"
          />
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="取消" @click="$emit('update:modelValue', false)" />
          <q-btn flat :label="isEditMode ? '保存' : '创建'" type="submit" />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import type { User } from 'src/types/user';

const props = defineProps<{
  modelValue: boolean;
  user?: User | null;
}>();

const emit = defineEmits(['update:modelValue', 'submit']);

const isEditMode = computed(() => !!props.user);

const initialFormData = {
  id: Date.now(),
  name: '',
  email: '',
  status: '启用',
};

const formData = ref<User>({ ...initialFormData });

watch(
  () => props.user,
  (newUser) => {
    if (newUser) {
      formData.value = { ...newUser };
    } else {
      formData.value = { ...initialFormData, id: Date.now() };
    }
  },
  { immediate: true },
);

function onSubmit() {
  emit('submit', { ...formData.value });
  emit('update:modelValue', false);
}
</script>
